<template>
  <div class="right-click-menu" v-show="showMenu" :style="`top:${position.y}px;left:${position.x}px;`" v-clickoutside="closeMenu">
    <div class="menu-item" v-for="(item, index) in menuList" :key="index" @click="clickItem(item.callback)">
      {{item.content}}
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      menuList: [],
      showMenu: false,
      position: {},
    }
  },
  created () {
    this.$bus.$on('rightMenu', this.openMenu)
  },
  beforeDestroy () {
    this.$bus.$off('rightMenu')
  },
  methods: {
    // 关闭菜单的回调
    closeMenu () {
      this.showMenu = false
      this.position = {}
      this.menuList = []
    },
    // 点击item的回调
    clickItem (callback) {
      callback()
      this.showMenu = false
    },

    // 打开菜单的回调
    openMenu ({ menuList, position }) {
      this.menuList = menuList;
      this.position = position
      this.showMenu = true;
    },
  },
}
</script>

<style scoped>
.right-click-menu {
  position: fixed;
  border: 1px solid #ccc;
  background-color: #fff;
  width: 120px;
  font-size: 12px;
  padding: 3px 0;
  border-radius: 5px;
}

.menu-item {
  border-bottom: 1px solid #ccc;
  padding: 4px 8px;
  cursor: pointer;
}

.menu-item:hover {
  background-color: #129611;
  color: white;
}

.menu-item:last-child {
  border: none;
}
</style>